package com;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateExample {

	public static void main(String[] args) throws Exception {

		/*获取当前时间*/
		long currentTime = System.currentTimeMillis();// 获取Long 型的当前时间
		Date currentDate = new Date();// 获取Date 型的当前时间
		
		/*long date 互转*/
		Date date = new Date(currentTime);//long 转 date
		currentDate.setTime(currentTime);//long 转 date
		long time = date.getTime();//date 转 long
		
		/*string date 互转*/
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
		String formatDate = formatter.format(currentDate);// date 转 string
		Date parseDate = formatter.parse(formatDate);// string 转 date
		
		/*日期计算*/
		time = time + 2 * 24 * 60 * 60 * 1000;//long 型日期加减计算
		
		/*日期相隔*/
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");    
		Date beginDate= format.parse("2007-12-24");    
		Date endDate= format.parse("2007-12-25");    
		long intervenesDay=(beginDate.getTime()-endDate.getTime())/(24*60*60*1000);    
		System.out.println("相隔的天数="+intervenesDay);   
		
		/*Calendar类的使用*/
		Calendar cal = Calendar.getInstance();// 取当前日期。
		cal.setTimeInMillis(cal.getTimeInMillis());
		cal.setTime(cal.getTime());
		System.out.println(formatter.format(cal.getTime()));
		
		//取日期的部分:
		int year =cal.get(Calendar.YEAR);    
		int month=cal.get(Calendar.MONTH)+1;//取月份要加1
		int day =cal.get(Calendar.DAY_OF_MONTH);    
		int hour =cal.get(Calendar.HOUR_OF_DAY);    
		int minute =cal.get(Calendar.MINUTE);    
		int seconds =cal.get(Calendar.SECOND);
		System.out.println(year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + seconds);
		
		//重新设置日期的某部分
		cal.set(Calendar.YEAR, 2010);
		cal.set(Calendar.MONTH, 0);
		cal.set(Calendar.DAY_OF_MONTH, 1);
		cal.set(Calendar.HOUR_OF_DAY, 1);
		cal.set(Calendar.MINUTE, 1);
		cal.set(Calendar.SECOND, 1);
		System.out.println(formatter.format(cal.getTime()));
		
		//重新计算日期的某部分
		cal.add(Calendar.YEAR, -2); 
		cal.add(Calendar.MONTH, 10); 
		cal.add(Calendar.DAY_OF_MONTH, 32); 
		cal.add(Calendar.HOUR, 25); 
		cal.add(Calendar.MINUTE, 65); 
		cal.add(Calendar.SECOND, 70); 
//		cal.roll(Calendar.SECOND, 70); 
//		cal.add(Calendar.DAY_OF_WEEK, 8); // 目前的時間加7天
		System.out.println(formatter.format(cal.getTime()));
		
		//判断当前月份的最大天数
		int maxDay=cal.getActualMaximum(Calendar.DAY_OF_MONTH);
		
	}

}
